import React, {useState, useEffect, useRef} from 'react';
import {Table, Button, Modal, Switch  } from 'antd'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm'
import {
    DeleteOutlined,
    AlignLeftOutlined,
    EditOutlined
  } from '@ant-design/icons';
const { confirm } = Modal
const UserList = () => {
    const [dataSource, setdataSource] = useState([]);
    //弹出框显示
    const [isAddvisible, setisAddvisible] = useState(false);
    // 角色数据
    const [roleLise, setroleLise] = useState([]);
    // 区域数据
    const [reightList, setreightList] = useState([]);
    //更新模态框显示
    const [Updatavisible, setUpdatavisible] = useState(false)
    //更新时判断是否禁用
    const [isupDatadisabled, setisupDatadisabled] = useState(false)
    //保存用于更新的值
    const [current, setcurrent] = useState(null)

    const addForm = useRef(null)
    const updataForm = useRef(null)


    const {roleId, region, username} = JSON.parse(localStorage.getItem("token"))
    //请求数据
    useEffect(()=>{
        axios.get('/users?_expand=role').then(res=>{
            const list = res.data
            setdataSource(roleId === 1?list:[
                ...list.filter(item=>item.username===username),
                ...list.filter(item=>item.region===region && item.roleId === 3)
            ])
        })
    } ,[region, roleId, username])
    //区域数据
    useEffect(()=>{
        axios.get('/regions').then(res=>{
            setreightList(res.data)
        })
    } ,[])
    //角色数据
    useEffect(()=>{
        axios.get('/roles').then(res=>{
            setroleLise(res.data)
        })
    } ,[])
      //table表格
      const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters:[
                ...reightList.map(item=>({
                    text: item.title,
                    value:item.value
                })),
                {
                    text: '全球',
                    value: ''
                }
            ],
            onFilter:(value, item)=>item.region === value,
            render: (region)=>{
                return <b>{region!==""?region:'全球'}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render:(role)=>{
                return role.roleName
            }
        },
        {
            title: '用户名',
            dataIndex: 'username'
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render:(roleState, item)=>{
                return <Switch  checked={roleState} onChange={()=>handleChange(item)} disabled={item.default}/>
            }
        },
        {
            title: '操作',
            render: (item)=>{
                return <div>
                    {/* 删除 */}
                    <Button type="primary" shape="circle"  danger icon={<DeleteOutlined />}
                    onClick={()=>confirMothod(item)}  disabled={item.default}/>
                    &nbsp;
                        {/* 更新 */}
                    <Button type="primary" shape="circle" icon={<AlignLeftOutlined/>}  disabled={item.default}
                    onClick={()=>handleUpdata(item)}/>
                </div>
            }
        },
      ];
          //删除弹框
    const confirMothod = (item) => {
        confirm({
            title: '您确定删除吗',
            icon: <EditOutlined />,
            onOk(){
                deleteMethod(item)
            },
            onCancel(){
                console.log("Can")
            }
        })
    }
       // 确认删除
    const deleteMethod = (item) => {
        setdataSource(dataSource.filter(data=>data.id!==item.id))
        axios.delete(`/users/${item.id}`)
    } 
    
    //添加Form用户
    const addFormOk= () =>{
        addForm.current.validateFields().then(value=>{
            setisAddvisible(false)
            axios.post(`/users`,{
                ...value,
                "roleState": true,
                "default": false
            }).then(res=>{
                setdataSource([...dataSource,
                    {...res.data,
                    role:roleLise.filter(item=>item.id===value.roleId)[0]
                    }
                    
                    ])
            })
        }).catch((err)=>{
            console.log(err)
        })
        
    }
    //更新Form用户更新按钮
    const UpdataFormOk = () => {
        updataForm.current.validateFields().then(value=>{
            setUpdatavisible(false)
            setdataSource(dataSource.map(data=>{
                if(data.id === current.id){
                    return {
                        ...data,
                        ...value,
                        role:roleLise.filter(item=>item.id===value.roleId)[0]
                    }
                }
                return data
            }))
            setisupDatadisabled(!isupDatadisabled)
            axios.patch(`/users/${current.id}`, value)
        })
    }
    //关闭状态
    const handleChange= (item) => {
        item.roleState = !item.roleState
        setdataSource([...dataSource])
        axios.patch(`/users/${item.id}`,{
            roleState: item.roleState
        })
    }
    //更新用户信息模态框
    const handleUpdata = (item) => {
        setTimeout(()=>{
            setUpdatavisible(true)
            if(item.roleId === 1){
                setisupDatadisabled(true)
            }else{
                setisupDatadisabled(false)
            }
            updataForm.current.setFieldsValue(item)
        },0)
        setcurrent(item)
    }
    return (
        <div>
            <Button type="primary" onClick={()=>{
                setisAddvisible(true)
            }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} rowKey={(item)=>item.id} pagination={{
                pageSize:5
            }}>
            </Table>

            <Modal
                visible={isAddvisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={()=>{
                    setisAddvisible(false)
                }}
                onOk={() => addFormOk()}
                >
                    <UserForm roleLise={roleLise} reightList={reightList} ref={addForm}></UserForm>
            </Modal>

            <Modal
                visible={Updatavisible}
                title="更新用户"
                okText="更新"
                cancelText="取消"
                onCancel={()=>{
                    setUpdatavisible(false)
                    setisupDatadisabled(!isupDatadisabled)
                }}
                onOk={() => UpdataFormOk()}
                >
                    <UserForm roleLise={roleLise} 
                    reightList={reightList} ref={updataForm} 
                    isupDatadisabled={isupDatadisabled} isUpdata = {true}></UserForm>
            </Modal>
        </div>
    );
};

export default UserList;